import UIManager from "./UIManager";
import Manager from "../Manager";
import { FMVCS } from "../../fgui/fmvc/FMVCS";
import { ConstDefine } from "../../game/common/ConstDefine"

export default class FGUIManager extends UIManager {
    root: fgui.GRoot = null;
    views: { [resName: string]: FMVCS.FView } = {};
    open(resName: string, script: typeof FMVCS.FView, uiTransition?: ConstDefine.Common.UITransition) {
        if (!this.root) {
            this.root = fgui.GRoot.create();
        }
        if(!this.views[resName]){
            Manager.res.getConfigByName(`resconfig`).then((configs) => {
                let config = configs[resName];
                if (!config) {
                    console.error(`[FGUIManager] --> resconfig中找不到 ${resName}`);
                    return;
                };
                fgui.UIPackage.loadPackage(config.path, (err) => {
                    if (err) return;
                    let view = fgui.UIPackage.createObject(config.pkgName, config.name, script) as FMVCS.FView;
                    view.makeFullScreen();
                    fgui.GRoot.inst.addChild(view);
                    this.views[resName] = view;
                    this.runViewTransition(view, uiTransition);
                    view.closeHandler = this.close.bind(this);
                    view.name = resName;
                });
            });
        }else{
            this.views[resName].removeFromParent();
            fgui.GRoot.inst.addChild(this.views[resName]);
            this.runViewTransition(this.views[resName], uiTransition);
            this.views[resName].onOpenCallBack();
        }
    }

    close(resName: string){
        let view = this.views[resName];

        if(view){
            view.dispose();
            this.views[resName] = null;
        }
    }

    runViewTransition(view: fgui.GComponent, uiTransition?: ConstDefine.Common.UITransition): Promise<any> {
        return new Promise((res, rej) => {
            if(!uiTransition){
                res();
                return;
            }
            switch(uiTransition){
                case ConstDefine.Common.UITransition.ScaleToBig: {
                    view.setScale(0, 0);
                    fgui.GTween.to2(view.scaleX, view.scaleY, 1, 1, 0.3)
                        .setTarget(view, view.setScale)
                        .setEase(fgui.EaseType.CircOut)
                        .onComplete(() => {
                            res();
                        }, this);
                    break;
                }
            }
        });
    }
}
